package com.vchello.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.vchello.bean.user.User;
import com.vchello.contants.MsgCode;
import com.vchello.contants.TitleCode;
import com.vchello.controller.constants.SubjectAttrConstants;
import com.vchello.util.JsonUtils;
import com.vchello.util.ToolUtil;

import net.sf.json.JSONObject;

/**
 * 
 * @author power
 *
 */
public class BaseController {

	static final String FLASH_MODEL_ATTRIBUTE = BaseController.class.getName();

	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;

	@ModelAttribute
	public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
		this.request = request;
		this.response = response;
		this.session = request.getSession();
	}
	
	protected User getUser(){
		User user = (User) session.getAttribute(SubjectAttrConstants.USER_AWARE_CONSTANT);
		return user;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Map<String, Object> getCurrent(HttpServletRequest request) {
		HttpSession session = request.getSession();
		Map<String, Object> flash = (Map) session.getAttribute(FLASH_MODEL_ATTRIBUTE);
		if (flash == null) {
			flash = new HashMap();
			session.setAttribute(FLASH_MODEL_ATTRIBUTE, flash);
		}
		return flash;
	}

	private static HttpServletRequest getRequest(RequestAttributes requestAttributes) {
		return ((ServletRequestAttributes) requestAttributes).getRequest();
	}

	protected String returnMsgSuccess(Model model) {
		return null;

	}

	protected String returnMsgError(Model model) {
		return null;

	}
	
	protected String getPath() {
		StringBuilder sb = new StringBuilder();
		sb.append("https://").append(request.getServerName()).append(request.getServletPath());

		if (ToolUtil.isNotEmpty(request.getQueryString())) {
			sb.append("?").append(request.getQueryString());
		}
		return sb.toString();
	}

	/**
	 * 微信弹框提示
	 * 
	 * @param title
	 * @return
	 */
	protected String getMessage(String title) {
		JSONObject json = new JSONObject();
		int code = TitleCode.getMessage(title);
		MsgCode.getMessage(code);
		json.put("title", title);
		json.put("msg", MsgCode.getMessage(code));
		return json.toString();

	}

	public static void put(String key, Object value) {
		getCurrent(getRequest(RequestContextHolder.currentRequestAttributes())).put(key, value);
	}

	public final void success(String success) {
		returnSuccessJson(success);
	}
	
	public final void success(JSONObject json) {
		returnSuccessJson(json);
	}
	
	public final void success(Object captchaCode, String message) {
		returnSuccessJson(captchaCode, message);
	}
	
	public final <T> void success(T obj) throws JSONException, IOException {
		returnSuccessJson(JsonUtils.objectToJson(obj));
	}

	 public final void error(String error) {
		 returnErrorJson(error);
	 }
	 
	 public final void errorValue(String error) {
		 returnErrorValue(error);
	 }
	 
	public void returnSuccess() {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", true);
		returnAjax(jsonObject.toString());
	} 
	 
	public void returnFalse() {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", false);
		returnAjax(jsonObject.toString());
	} 

	private String returnErrorJson(Object data) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", false);
		jsonObject.put("data", data);
		return returnAjax(jsonObject.toString());
	}
	
	private String returnErrorValue(String data) {
		return returnAjax(data);
	}
	
	private String returnSuccessJson(Object data) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", true);
		jsonObject.put("data", data);
		return returnAjax(jsonObject.toString());
	}
	
	private String returnSuccessJson(Object captchaCode, String message) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("status", true);
		jsonObject.put("captchaCode", captchaCode);
		jsonObject.put("message", message);
		return returnAjax(jsonObject.toString());
	}

	/**
	 * json
	 * 
	 * @param request
	 * @param response
	 * @param result
	 * @return
	 */
	private String returnAjax(String result) {
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			String ss = result == null ? "" : result;
			out.write(ss);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.flush();
				out.close();
			}
		}
		request.setAttribute("jsonData", result);
		return result;
	}

	public static enum MessageType {
		info, success, warning, error;
	}

}
